<template>
    <div id="welcome">
        <!--  导航面包屑      -->
        <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>欢迎</el-breadcrumb-item>
        </el-breadcrumb>
<el-row :gutter="20" style="margin-bottom: 2vh">
  <el-col :span="6" >
    <el-card>
        <el-row>
          <el-col class="text-box" :span="16">
           <span>
             前台总坐席数
           </span>
            <div>
              {{ formatNumberString(this.allCount.seatCount) }}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="icon-box">
              <img src="../assets/icon_zx.png" alt="">
            </div>
          </el-col>
        </el-row>
    </el-card>
  </el-col>
  <el-col :span="6">
    <el-card>
      <el-row>
        <el-col class="text-box"  :span="16">
           <span>
             总客户数
           </span>
          <div>
            {{ formatNumberString(this.allCount.clientCount) }}
          </div>
        </el-col>
        <el-col :span="8">
          <div class="icon-box">
            <img src="../assets/icon_user.png" alt="">
          </div>
        </el-col>
      </el-row>
    </el-card>
  </el-col>
  <el-col :span="6">
    <el-card>
      <el-row>
        <el-col class="text-box"  :span="16">
           <span>
             总部门数
           </span>
          <div>
            {{ formatNumberString(this.allCount.deptCount) }}
          </div>
        </el-col>
        <el-col :span="8">
            <div class="icon-box">
              <img src="../assets/icon_bm.png" alt="">
            </div>
        </el-col>
      </el-row>
    </el-card>
  </el-col>
  <el-col :span="6">
    <el-card>
      <el-row>
        <el-col class="text-box"  :span="16">
           <span>
             今日拨打量
           </span>
          <div>
            {{ formatNumberString(this.allCount.callCount) }}
          </div>
        </el-col>
        <el-col :span="8">
          <div class="icon-box">
            <img src="../assets/icon_tel.png" alt="">
          </div>
        </el-col>
      </el-row>
    </el-card>
  </el-col>
</el-row >
      <el-row :gutter="20">
        <el-col :span="15">
          <el-card >
              <h3 style="line-height: 3vh;margin: 0 0 5vh; ">
                账户统计
              </h3>
            <div>
              <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
              <div id="accountMain" style="width: 700px;height:400px;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card>
            <h3 style="line-height: 3vh;margin: 0 0 5vh; ">
              部门信息
            </h3>
            <div>
              <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
              <div id="deptMain" style="width: 400px;height:400px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
</template>
<script>
import echarts from "echarts";
    import aplayer from "vue-aplayer";
    export default {
        components: {
            //别忘了引入组件
            aplayer: aplayer
        },

        data() {
            return {
              deptList:[],
              adminNums:[],
              userNums:[],
             allNums:[],
              accountNames:[],
              allCount:{
                seatCount:0,
                clientCount:0,
                deptCount:0,
                callCount:0
              },
                xData: [],
                yData: [],
                myData: [],
                value: new Date(),
                userInfo: {},
                tableInfo: [],
                musicList:[{
                    "artist": "Eminem",
                    "lrc": "",
                    "title": "Airplanes",
                    "src": "http://music.163.com/song/media/outer/url?id=26714821.mp3",
                    "pic": "http://p4.music.126.net/H9HJibEzTL34aIT6nsqKsQ==/5682276092402519.jpg"
                },{
                    "artist": "Tinashe",
                    "lrc": "",
                    "title": "Story of Us",
                    "src": "http://music.163.com/song/media/outer/url?id=1403428061.mp3",
                    "pic": "http://p3.music.126.net/l2XttTpEa14IEZtUsQX1HA==/109951164486978461.jpg"
                }, {
                    "artist": "Chris Brown",
                    "lrc": "",
                    "title": "War For You",
                    "src": "http://music.163.com/song/media/outer/url?id=30431534.mp3",
                    "pic": "http://p3.music.126.net/YWkl1JXVKm7bOBAew72lGg==/109951163958771792.jpg"
                }, {
                    "artist": "Sarah Darling",
                    "lrc": "",
                    "title": "Jack of Hearts",
                    "src": "http://music.163.com/song/media/outer/url?id=19132440.mp3",
                    "pic": "http://p4.music.126.net/4q3kpn5VLo3x7hVWttj0QA==/109951164802108652.jpg"
                }, {
                    "artist": "Benjamin Ingrosso",
                    "lrc": "",
                    "title": "Costa Rica",
                    "src": "http://music.163.com/song/media/outer/url?id=1372897252.mp3",
                    "pic": "http://p4.music.126.net/mmm97zC81t73rToPFuXXnw==/109951164159882466.jpg"
                }, {
                    "artist": "Yo Trane",
                    "lrc": "",
                    "title": "Affection",
                    "src": "http://music.163.com/song/media/outer/url?id=1393553542.mp3",
                    "pic": "http://p4.music.126.net/T_vdbfQPO4HE4zVE_8rgCQ==/109951164389023010.jpg"
                }]
            };
        },
        methods: {
          drawAccount(){
            var chartDom = document.getElementById('accountMain');
            var myChart = echarts.init(chartDom);
            var option;

            option = {
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  crossStyle: {
                    color: '#999'
                  }
                }
              },
              toolbox: {
                feature: {
                  dataView: { show: true, readOnly: false },
                  magicType: { show: true, type: ['line', 'bar'] },
                  restore: { show: true },
                  saveAsImage: { show: true }
                }
              },
              legend: {
                data: ['管理员数量', '普通用户数量', '总人数']
              },
              xAxis: [
                {
                  type: 'category',
                  data: JSON.parse(JSON.stringify(this.accountNames)),
                  axisLabel: {
                    show: true, // 确保标签显示
                    interval: 0, // 强制显示所有标签
                    rotate: 45, // 标签旋转角度（防止重叠）
                    margin: 15,  // 标签与轴线间距
                    formatter: function(value) {
                      // 过长文本处理（可选）
                      return value.length > 10 ? value.substring(0,8)+'...' : value;
                    }
                  },
                  axisTick: {
                    alignWithLabel: true // 刻度与标签对齐
                  },
                  axisPointer: {
                    type: 'shadow'
                  }
                }
              ],
              yAxis: [
                {
                  type: 'value',
                  name: '管理员数量',
                  min: 0,
                  max: 50,
                  interval: 5,
                  axisLabel: {
                    formatter: '{value}'
                  }
                },
                {
                  type: 'value',
                  name: '普通用户数量',
                  min: 0,
                  max: 50,
                  interval: 5,
                  axisLabel: {
                    formatter: '{value}'
                  }
                }
              ],
              series: [
                {
                  name: '管理员数量',
                  color:'#2481e9',
                  type: 'bar',
                  tooltip: {
                    valueFormatter: function (value) {
                      return value;
                    }
                  },
                  data: JSON.parse(JSON.stringify(this.adminNums)),
                },
                {
                  name: '普通用户数量',
                  color:'#66b42a',
                  type: 'bar',
                  tooltip: {
                    valueFormatter: function (value) {
                      return value
                    }
                  },
                  data: JSON.parse(JSON.stringify(this.userNums)),
                },
                {
                  name: '总人数',
                  color:'#f6ae1c',
                  type: 'line',
                  yAxisIndex: 1,
                  tooltip: {
                    valueFormatter: function (value) {
                      return value
                    }
                  },
                  data:JSON.parse(JSON.stringify(this.allNums)),
                }
              ]
            };

            option && myChart.setOption(option);
          },
          drawDept(){
            // 定义色系池（可扩展）
            const colorPools = {
              techBlue: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de','#ff9f40', '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4'], // 科技蓝调
              pastel: ['#9d79d6', '#67ccb3', '#f5a623', '#eb4d4b', '#6ab0de'], // 马卡龙色
              darkMode: ['#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80'] // 暗色系
            };
            var chartDom = document.getElementById('deptMain');
            var myChart = echarts.init(chartDom);
            var option;
            option = {
              color: colorPools.techBlue, // 指定色系
              tooltip: {
                trigger: 'item'
              },
              legend: {
                top: '5%',
                left: 'center'
              },
              series: [
                {
                  name: 'Access From',
                  type: 'pie',
                  radius: ['40%', '70%'],
                  avoidLabelOverlap: false,
                  itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                  },
                  label: {
                    show: false,
                    position: 'center'
                  },
                  emphasis: {
                    label: {
                      show: true,
                      fontSize: 40,
                      fontWeight: 'bold'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: JSON.parse(JSON.stringify(this.deptList))
                }
              ]
            };

            option && myChart.setOption(option);
          },
            /**
             * 点击获取源码
             */
            getPage(url) {
                const w = window.open("about:blank");
                w.location.href = url;
            },
            /**
             * 加载登入报表数据
             */
            async loginReport(username) {
                const { data: res } = await this.$http.post("system/loginLog/loginReport", {
                    username: username
                });
                if(!res.success){
                    return this.$message.error("获取登入报表数据失败:" + res.msg);
                } else {
                    const $this = this;
                    this.xData = [];
                    this.yData = [];
                    this.myData = [];
                    res.data.all.forEach(e1 => {
                        $this.xData.push(e1.days);
                        $this.yData.push(e1.count);
                    });

                    for (let i = 0; i < this.xData.length; i++) {
                        let count = 0;
                        for (let j = 0; j < res.data.me.length; j++) {
                            if ($this.xData[i] === res.data.me[j].days) {
                                count = res.data.me[j].count;
                                break;
                            } else {
                                count = 0;
                            }
                        }
                        $this.myData.push(count);
                    }
                }
                this.draw();
            },
          formatNumberString(str) {
            console.log(str)
          return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
          },
          /**
           * 查询所有信息总数
           */
          async getAllCount(){
            const { data: res } = await this.$http.get("/system/welcome/getCount");
            if(!res.success){
              return this.$message.error("获取登录日志列表失败:"+res.data.errorMsg);
            }
            this.allCount=res.data;
          },
          /**
           * 查询account信息
           */
          async getAccountInfo(){
            const { data: res } = await this.$http.get("/system/welcome/getAccountInfo");
            if(!res.success){
              return this.$message.error("获取登录日志列表失败:"+res.data.errorMsg);
            }
            console.log(res.data)
            res.data.forEach(e1 => {
              this.accountNames.push(e1.accountName);
              this.adminNums.push(e1.adminNum);
              this.userNums.push(e1.userNum);
              this.allNums.push(e1.adminNum+e1.userNum);
            })
            console.log( JSON.parse(JSON.stringify(this.accountNames)))
            console.log( JSON.parse(JSON.stringify(this.adminNums)))
            console.log( JSON.parse(JSON.stringify(this.userNums)))
            console.log( JSON.parse(JSON.stringify(this.allNums)))
            this.drawAccount();

          },
          //加载菜单树
          async getDeptTree() {
            const {data: res} = await this.$http.get("system/dept_emp/findDepartmentList",{
              params:this.queryMap
            });
            if (res.success) {
              this.deptList = this.transformDeptStructure(res.data.rows);
            }
            this.drawDept();
          },
          transformDeptStructure(data) {
            const transform = (node) => {
              const newNode = {
                name: node.deptName,
                value: node.total || 0 // 强制所有节点必须有 value
              };

              // 递归处理子节点，并过滤空 children
              if (node.children && node.children.length > 0) {
                const children = node.children.map(transform).filter(c =>
                    c.value > 0 || (c.children && c.children.length > 0)
                );

                if (children.length > 0) { // 仅当存在有效子节点时添加 children
                  newNode.children = children;
                  newNode.value += children.reduce((sum, c) => sum + c.value, 0); // 累加子节点值
                }
              }

              return newNode;
            };

            return data.map(transform).filter(n =>
                n.value > 0 || (n.children && n.children.length > 0)
            );
          },
        },

        created() {
            this.userInfo = this.$store.state.userInfo;
            const roles = this.userInfo.isAdmin ? "超级管理员" : this.userInfo.roles;
            this.tableInfo.push({
              userName: this.userInfo.userName,
              nickName: this.userInfo.nickName,
                department: this.userInfo.department,
                roles: roles
            });
          // this.noticeContent();
          this.getAllCount();
        },
        mounted: function() {
          this.getAccountInfo();
          this.getDeptTree();

        },

    };
</script>

<style scoped>
.text-box span{
  display: block;
  font-size: 1.8vh;
  margin: 1.8vh 0;
  color: #444;
}
.text-box div{
  font-size: 4vh;
}
.icon-box img{
  width: 9vh;
}
.icon-box{
  width: 8vh;
  height: 8vh;
  //background-color: #4c88ff55;
  padding: 2vh;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
    .el-carousel__item h3 {
        color: #475669;
        font-size: 14px;
        opacity: 0.75;
        line-height: 200px;
        margin: 0;
    }
    .popups{
      width: 100%;
      height: 100%;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 100;
    }
    .popups .el-main{
      background-color: #bfdaf2;
      margin: 33vh auto;
    }
    .popups .el-main .header{
      display: flex;
      justify-content: center;
    }
    .popups .el-main .header button {
      flex-shrink: 0; /* 防止收缩 */
      border: none;
    }
    .small {
      margin: -20px 60px 30px 60px;
      display: -webkit-box;
      -webkit-line-clamp: 3; /* 限制显示的行数为3行 */
      -webkit-box-orient: vertical;
      overflow: auto; /* 当内容超出时显示滚动条 */

    }

    .custom-carousel-item {
      transition: all 0.0s ease; /* 这里的 0.5s 就是过渡时间，可以按需调整，ease 是过渡效果的函数，可以换为其他如 linear 等 */
    }

    /* 按钮禁用（延时期间）时的样式 */
    .el-button.disabled {
      background-color: #ccc!important;
      color: #999!important;
      cursor: not-allowed!important;
      border-color: #ccc!important;
      width: 150px;height: 30px
    }

    /* 倒计时文本（秒字）的样式，初始显示 */
    .el-button.countdown-text {
      display: inline;
    }

    /* 倒计时结束后隐藏秒字的样式 */
    .el-button.countdown-finished.countdown-text {
      display: none;
    }
</style>
